package com.wnxy.consumer.f_confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.impl.AMQImpl;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ConfirmConsumer {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "queue-confirm",durable = "true",arguments = {
                    @Argument(name = "x-dead-letter-exchange",value = "exchange-dlx"),
                    @Argument(name = "x-dead-letter-routing-key",value = "dlx.ooo"),
                    @Argument(name = "x-message-ttl",type = "java.lang.Long",value = "10000"),
                    @Argument(name = "x-max-length",type = "java.lang.Long",value = "5"),
            }),
            exchange = @Exchange(name = "exchange-confirm",type = ExchangeTypes.TOPIC),
            key = {"confirm.*"}
    ))
    public void handlerMsg(Channel channel, Message message, @Payload OrderDto orderDto) throws IOException {
        try {
            //int i = 1/0;
            System.out.println("消息确认：" + orderDto);
            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        } catch (Exception e) {
            e.printStackTrace();
            // 出现异常，获取重投标记
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            if (redelivered) {
                // 说明重投过，重投过的消息，拒绝----> 死信
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                System.out.println("消息消费失败，重投失败，拒绝！");
            } else {
                // 没有重投过，重新投递
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,true);
                System.out.println("消息消费失败，重投！");
            }
        }
    }
}